<?php

/**
 * @name ProductController
 * @desc 控制器
 */
class ProductController extends AdminCommonController
{
    /**
     * 默认动作
     */
    public function indexAction()
    {
        echo "Hello product";
        return false;
    }

    //店铺商品列表
    public function listAction(){
       $params = $this->jsonData();

       $row = $params['pageSize'] ?? 12;
       $page = $params['page'] ?? 1;

       $shopProductSpecsModel = ShopProductSpecsModel::getSingleton();

       $cond = [];

        if(isset($params['cate_id']) && $params['cate_id']){
            $cond['p.cate_id'] = $params['cate_id'];
        }
        if(isset($params['is_show'])){
            $cond['sps.is_show'] = $params['is_show'];
        }
        if(isset($params['product_name']) && trim($params['product_name'])){
            $cond['p.product_name#like'] = trim($params['product_name']). '%';
        }
        if(isset($params['product_id']) && intval($params['product_id'])){
            $cond['p.product_id'] = intval($params['product_id']);
        }
        if(isset($params['date_s']) && $params['date_s'] != ''){
           $cond['p.create_time#>='] = $params['date_s'];
        }
        if(isset($params['date_e']) && $params['date_e'] != ''){
           $cond['p.create_time#<'] = $params['date_e'];
        }

        //非超级管理员
        $adminInfo = AdminModel::getSingleton()->find(['admin_id'=> $this->admin_info['admin_id']], 'admin_type,moble,user_id');
        if($adminInfo['admin_type']==1 || $adminInfo['admin_type'] == 2){
            $userInfo = UserModel::getSingleton()->find(['user_id'=> $adminInfo['user_id']], 'user_type,shop_id,shop_user_id');
            if($userInfo['user_type'] == 1){
                $cond['sps.shop_id'] = $userInfo['shop_user_id'];
            }else if($userInfo['user_type'] == 2){
                $cond['sps.shop_id'] = $userInfo['shop_id'];
            }
        }

        $list = $shopProductSpecsModel->db
            ->field('p.*,c.cate_title')
            ->alias('sps')
            ->join(['product', 'p'], ['sps.product_id'=> 'p.product_id'], 'left join')
            ->join(['cate', 'c'], ['p.cate_id'=> 'c.cate_id'], 'left join')
            ->where_c($cond)
            ->order('sps.id desc')
            ->groupby('sps.product_id')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $shopProductSpecsModel->db
            ->alias('sps')
            ->join(['product', 'p'], ['sps.product_id'=> 'p.product_id'], 'left join')
            ->join(['cate', 'c'], ['p.cate_id'=> 'c.cate_id'], 'left join')
            ->where_c($cond)
            ->groupby('sps.product_id')
            ->count();
//       $list = $productModel->db
//           ->field('p.*,c.cate_title')
//           ->alias('p')
//           ->join(['cate', 'c'], ['p.cate_id'=> 'c.cate_id'], 'left join')
//           ->where_c($cond)
//           ->order('p.product_id desc')
//           ->limit(($page - 1) * $row, $row)
//           ->select();
//       $total = $productModel->db
//           ->alias('p')
//           ->join(['cate', 'c'], ['p.cate_id'=> 'c.cate_id'], 'left join')
//           ->where_c($cond)
//           ->count();

//       $prodcutSpecsModel = ProductSpecsModel::getSingleton();
       foreach ($list as &$val){
           $where = ['sps.product_id'=> $val['product_id']];
           if($adminInfo['admin_type']==1 || $adminInfo['admin_type'] == 2){
               $where['sps.shop_id'] = $cond['sps.shop_id'];
           }
           $val['product_specs'] = $shopProductSpecsModel->db
               ->field('sps.*,ps.spec_name_full,ps.unit_money,ps.point,ps.spec_stock,ps.sale_num,ps.spec_stock_total,sps.shop_spec_stock_total')
               ->alias('sps')
               ->join(['product_specs', 'ps'], ['sps.spec_id'=> 'ps.spec_id'], 'left join')
               ->where_c($where)
               ->order('sps.id desc')
               ->select();
           if(count($val['product_specs'])>0){
               $val['spec_stock_total'] = $val['product_specs'][0]['spec_stock_total'];
               $val['shop_spec_stock_total'] = $val['product_specs'][0]['shop_spec_stock_total'];
           }
       }

       $data = [
           'list' => $list,
           'total' => intval($total),
           'current'   => intval($page),
           'pageSize'  => intval($row),
           'page'  => intval($page)
       ];

       $this->ajaxReturn(0, '', $data);
    }

    //云端商品列表
    public function purchaseAction(){
        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $productModel = ProductModel::getSingleton();

        $cond = [];

        if(isset($params['cate_id']) && $params['cate_id']){
            $cond['p.cate_id'] = $params['cate_id'];
        }
        if(isset($params['is_show'])){
            $cond['p.is_show'] = $params['is_show'];
        }
        if(isset($params['product_name']) && trim($params['product_name'])){
            $cond['p.product_name#like'] = trim($params['product_name']). '%';
        }
        if(isset($params['product_id']) && intval($params['product_id'])){
            $cond['p.product_id'] = intval($params['product_id']);
        }
        if(isset($params['date_s']) && $params['date_s'] != ''){
            $cond['p.create_time#>='] = $params['date_s'];
        }
        if(isset($params['date_e']) && $params['date_e'] != ''){
            $cond['p.create_time#<'] = $params['date_e'];
        }

       $list = $productModel->db
           ->field('p.*,c.cate_title')
           ->alias('p')
           ->join(['cate', 'c'], ['p.cate_id'=> 'c.cate_id'], 'left join')
           ->where_c($cond)
           ->order('p.product_id desc')
           ->limit(($page - 1) * $row, $row)
           ->select();
       $total = $productModel->db
           ->alias('p')
           ->join(['cate', 'c'], ['p.cate_id'=> 'c.cate_id'], 'left join')
           ->where_c($cond)
           ->count();

       $prodcutSpecsModel = ProductSpecsModel::getSingleton();
       $shopPurchaseCart = ShopPurchaseCartModel::getSingleton();
        foreach ($list as &$val){
            $where = ['product_id'=> $val['product_id']];
            if(isset($params['is_show'])){
                $where['is_show'] = $params['is_show'];
            }
            $product_specs = $prodcutSpecsModel->findAll($where);
            if($this->admin_info['admin_type'] == 2){
                foreach ($product_specs as &$item){
                    $exsit = $shopPurchaseCart->count(['shop_id'=> $this->admin_info['shop_id'], 'spec_id'=> $item['spec_id']]);
                    $item['has_cart'] = $exsit? 1: 0;
                    $item['cnause_stock_num'] = $item['spec_stock'] - $item['f_spec_stock'];
                }
            }
            $val['product_specs'] = $product_specs;
            $val['spec_stock_total'] = $val['product_specs'][0]['spec_stock_total'];
            //是否已采购

        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //采购清单
    public function purchasecartAction(){
        if($this->admin_info['admin_type'] != 2){
            $this->ajaxReturn(400, '必须实体店才能采购');
        }

        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $shopPurchaseCartModel = ShopPurchaseCartModel::getSingleton();

        $cond = [];

        if(isset($params['cate_id']) && $params['cate_id']){
            $cond['p.cate_id'] = $params['cate_id'];
        }
        if(isset($params['is_show'])){
            $cond['p.is_show'] = $params['is_show'];
        }
        if(isset($params['product_name']) && trim($params['product_name'])){
            $cond['p.product_name#like'] = trim($params['product_name']). '%';
        }
        if(isset($params['product_id']) && intval($params['product_id'])){
            $cond['p.product_id'] = intval($params['product_id']);
        }
        if(isset($params['date_s']) && $params['date_s'] != ''){
            $cond['p.create_time#>='] = $params['date_s'];
        }
        if(isset($params['date_e']) && $params['date_e'] != ''){
            $cond['p.create_time#<'] = $params['date_e'];
        }
        $cond['spc.shop_id'] = $this->admin_info['shop_id'];


        $list = $shopPurchaseCartModel->db
            ->field('p.*,c.cate_title,spc.shop_id')
            ->alias('spc')
            ->join(['product', 'p'], ['spc.product_id'=> 'p.product_id'], 'left join')
            ->join(['cate', 'c'], ['p.cate_id'=> 'c.cate_id'], 'left join')
            ->where_c($cond)
            ->order('spc.id desc')
            ->groupby('spc.product_id')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $shopPurchaseCartModel->db
            ->alias('spc')
            ->join(['product', 'p'], ['spc.product_id'=> 'p.product_id'], 'left join')
            ->join(['cate', 'c'], ['p.cate_id'=> 'c.cate_id'], 'left join')
            ->where_c($cond)
            ->groupby('spc.product_id')
            ->count();

        foreach ($list as &$val){
            $where = ['spc.product_id'=> $val['product_id']];
            $cartList = $shopPurchaseCartModel->db
                ->field('spc.*,ps.spec_name_full,ps.unit_money,ps.point,ps.spec_stock,ps.f_spec_stock,ps.sale_num,ps.spec_stock_total')
                ->alias('spc')
                ->join(['product_specs', 'ps'], ['spc.spec_id'=> 'ps.spec_id'], 'left join')
                ->where_c($where)
                ->order('spc.id desc')
                ->select();
            //验证购物车库存是否超出总仓库存
            foreach ($cartList as &$item){
                $canuse_stock = $item['spec_stock'] - $item['f_spec_stock'];
                $item['canuse_stock'] = $canuse_stock;
                if( $item['num']> $canuse_stock ){
                    $item['num'] = $canuse_stock;
                    //更新库存
                    $shopPurchaseCartModel->update(['id'=> $item['id']], ['num'=> $canuse_stock]);
                }
            }
            $val['product_specs'] = $cartList;
            $val['spec_stock_total'] = $val['product_specs'][0]['spec_stock_total'];
        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //采购操作
    public function dopurchaseAction(){
        if($this->admin_info['admin_type'] !=2){
            $this->ajaxReturn(400, '只有实体店才能采购');
        }

        $params = $this->jsonData();
        if(!isset($params['pay_money']) || !$params['pay_money']){
            $this->ajaxReturn(400, '必须输入已支付的款项');
        }
        if(!isset($params['remark']) || !$params['remark']){
            $this->ajaxReturn(400, '必须输入支付备注');
        }

        $shopPurchaseCartModel = ShopPurchaseCartModel::getSingleton();
        $list = $shopPurchaseCartModel->db
            ->field('spc.*,ps.unit_money,p.product_name,ps.spec_name_full,ps.spec_stock,ps.f_spec_stock')
            ->alias('spc')
            ->join(['product_specs', 'ps'], ['spc.spec_id'=> 'ps.spec_id'], 'left join')
            ->join(['product', 'p'], ['spc.product_id'=> 'p.product_id'], 'left join')
            ->where_c(['spc.shop_id'=> $this->admin_info['shop_id'], 'ps.is_show'=> 1])
            ->select();

        $total = 0;
        foreach ($list as $val){
            if(intval($val['num']) <= 0){
                $this->ajaxReturn(400, '每个规格必须至少采购一件');
            }
            $canuse_stock = $val['spec_stock'] - $val['f_spec_stock'];
            if($canuse_stock == 0 || $val['num'] > $canuse_stock){
                $this->ajaxReturn(400, $val['product_name'] .' '.$val['spec_name_full'].'库存已不足，请刷新页面重试');
            }
            $total += $val['unit_money'] * $val['num'];
        }
        if($total == 0 || $total!= $params['pay_money']){
            $this->ajaxReturn(400,'支付金额不对，或者库存不足，请金额或刷新页面重试。');
        }

        $curTime = time();
        $addData = [
            'status'    => 0,
            'shop_id'   => $this->admin_info['shop_id'],
            'pay_money'       => $total,
            'remark'          => $params['remark'],
            'create_time'   => $curTime
        ];
        try{
            \Vendor\DB::startTrans();

            //log表
            $purchaseLogmodel = PurchaseLogModel::getSingleton();
            $log_id = $purchaseLogmodel->add($addData);
            if(!$log_id){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '操作失败！请重试');
            }

            $shopPurchaseSpecsModel = ShopPurchaseSpecsModel::getSingleton();
            $productSpecsModel = ProductSpecsModel::getSingleton();
            //记录
            foreach ($list as $val){
                $addData = [
                    'log_id'        => $log_id,
                    'spec_id'       => $val['spec_id'],
                    'product_id'    => $val['product_id'],
                    'product_name'  => $val['product_name'],
                    'spec_name_full'    => $val['spec_name_full'],
                    'unit_money'    => $val['unit_money'],
                    'num'           => $val['num'],
                    'create_time'   => $curTime
                ];

                if(!$shopPurchaseSpecsModel->add($addData)){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '报单失败，请刷新页面重试', $shopPurchaseSpecsModel->errMsg);
                }

                //冻结平台库存
                if (!$productSpecsModel->setInc(['spec_id'=> $val['spec_id']], 'f_spec_stock', $val['num'])){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '报单失败，请刷新页面重试.', $productSpecsModel->errMsg);
                }
            }

            //清空购物清单
            if(!$shopPurchaseCartModel->delete(['id#>'=> 0, 'shop_id'=> $this->admin_info['shop_id']])){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '报单失败，请刷新页面重试..', $shopPurchaseCartModel->errMsg);
            }

            \Vendor\DB::commit();
        }catch(Exception $e){
            \Vendor\DB::rollback();
            $this->ajaxReturn(400, '报单失败，请返回重试', $e->getMessage());
        }


        $this->ajaxReturn(0, '操作成功');
    }


    //所有分类
    public function catelistAction(){

        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $cateModel = CateModel::getSingleton();

        $cond = [];

        $list = $cateModel->db
            ->where($cond)
            ->order('sort desc')
            ->limit(($page - 1) * $row, $row)
            ->select();
        $total = $cateModel->db
            ->where($cond)
            ->count();

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //添加分类
    public function cateaddAction(){
        $params = $this->jsonData();

        $cateModel = CateModel::getSingleton();
        if(!$cateModel->add($params)){
            $this->ajaxReturn(400, $cateModel->errMsg);
        }
        $this->ajaxReturn(0, '添加成功');
    }

    //修改分类
    public function cateeditAction(){
        $params = $this->jsonData();

        if(!$params || empty($params) || !isset($params['cate_id'])){
            $this->ajaxReturn(400, '修改失败');
        }

        $cateModel = CateModel::getSingleton();
        $res = $cateModel->update(['cate_id'=> $params['cate_id']],
            [
                'cate_title'    => $params['cate_title'],
                'is_show'       => $params['is_show'],
                'sort'          => $params['sort'],
                'update_time'   => time()
            ]
        );

        if(!$res){
            $this->ajaxReturn(400, '修改失败');
        }
        $this->ajaxReturn(0, '修改成功');
    }

    public function detailAction(){
        $params = $this->jsonData();

        if(!isset($params['product_id']) || !$params['product_id']){
            $this->ajaxReturn(400, '未获取到商品ID');
        }
        $productModel = ProductModel::getSingleton();
        $detail = $productModel->find(['product_id'=> $params['product_id']]);
        if(!$detail){
            $this->ajaxReturn(400, '商品不存在');
        }
//        if($detail['is_show'] == 0 && !isset($params['is_admin'])){
//            $this->ajaxReturn(400, '商品已经下架');
//        }
        $detail['gallery_img'] = json_decode($detail['gallery_img']);

        //规格列表
        $productSpecs = ProductSpecsModel::getSingleton()->findAll(['product_id'=> $detail['product_id']]);
        foreach ($productSpecs as &$val){
            $val['is_add'] = true;
        }

        $returnData = [
            'product'   => $detail,
            'userSpecItemList'  => $productSpecs
        ];

        $this->ajaxReturn(0, 'success', $returnData);
    }

    //删除规格
    public function delspecAction(){
        $params = $this->jsonData();

        if(!isset($params['spec_id']) || !$params['spec_id']){
            $this->ajaxReturn(400, '未获取到数据标识');
        }
        $productSpecModel = ProductSpecsModel::getSingleton();
        if(!$productSpecModel->delete(['spec_id'=> $params['spec_id'], 'sale_num'=> 0])){
            $this->ajaxReturn(400, '删除失败，规格不存在或者已售出');
        }
        $this->ajaxReturn(0, '删除成功', $productSpecModel->errMsg);
    }

    //添加商品
    public function addAction(){
        $params = $this->jsonData(false);

        $productModel = ProductModel::getSingleton();
        $gallery_img = [];
        foreach($params['product']['gallery_img'] as $val){
            $gallery_img[] = [
                'status'    => 'finished',
                'name'      => $val['name'],
                'url'       => $val['url']
            ];
        }

        $params['product']['gallery_img'] = json_encode($gallery_img);

        $curTime = time();
        try{
            \Vendor\DB::startTrans();

            //计算总各规格总库存
            $spec_stock_total = 0;
            foreach ($params['product_specs'] as &$item){
                $spec_stock_total += $item['spec_stock'];
            }

            //商品基础信息
            $params['product']['create_time'] = $curTime;
            $params['product']['stock_num'] = $spec_stock_total;
            $product_id = $productModel->add($params['product']);
            if(!$product_id){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '添加失败', $productModel->errMsg);
            }

            //商品规格属性
            $specItemsModel = SpecItemsModel::getSingleton();
            $spec_items = array_filter($params['spec_items']);
            $spec_items_index = [];
            foreach($spec_items as $key=>$val){
                foreach ($val as $vv){
                    $item_id = $specItemsModel->add([
                        'cat_id'        => $key,
                        'product_id'    => $product_id,
                        'item_name'     => $vv,
                    ]);
                    if(!$item_id){
                        \Vendor\DB::rollback();
                        $this->ajaxReturn(400, '添加失败.', $specItemsModel->errMsg);
                    }
                    $spec_items_index[$vv] = ['cat_id'=> $key, 'item_id'=> $item_id];
                }
            }

            //商品规格列表
            $productSpecsModel = ProductSpecsModel::getSingleton();
            foreach ($params['product_specs'] as &$val){
                $spec_ids_arr = [];
                $spec_name_full_arr = explode(' ', $val['spec_name_full']);
                foreach ($spec_name_full_arr as $vv){
                    $spec_ids_arr[] = 's'.$spec_items_index[$vv]['cat_id'].'#'.$spec_items_index[$vv]['item_id'];
                }
                $spec_ids = implode('_', $spec_ids_arr);
                if(!$productSpecsModel->add([
                    'product_id'        => $product_id,
                    'spec_name_full'    => $val['spec_name_full'],
                    'spec_ids'          => $spec_ids,
                    'point'             => $val['point'],
                    'unit_money'        => $val['unit_money'],
                    'spec_stock'        => $val['spec_stock'],
                    'spec_stock_total'  => $spec_stock_total,
                    'warn_stock'        => $val['warn_stock'],
                    'is_default'        => $val['is_default'],
                    'is_show'           => 1,
                    'create_time'       => $curTime
                ])){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '添加失败..', $productSpecsModel->errMsg);
                }
            }

            \Vendor\DB::commit();
        }catch(Exception $e){
            \Vendor\DB::rollback();
            $this->ajaxReturn(400, '下单失败，请返回重试', $e->getMessage());
        }

        $this->ajaxReturn(0, '添加成功');
    }

    public function editAction(){
        $params = $this->jsonData(false);

        if(!isset($params['product']['product_id']) || !$params['product']['product_id']){
            $this->ajaxReturn(400, '未获取到商品ID');
        }

        if(isset($params['product']['product_name']) && \Vendor\Kstring::_strlen($params['product']['product_name'])>40){
            $this->ajaxReturn(400, '商品名称不能大于40个字符');
        }

        if(isset($params['product']['gallery_img'])){
            $gallery_img = [];
            foreach($params['product']['gallery_img'] as $val){
                $gallery_img[] = [
                    'status'    => 'finished',
                    'name'      => $val['name'],
                    'url'       => $val['url']
                ];
            }
            $params['product']['gallery_img'] = json_encode($gallery_img);
        }

        $productModel = ProductModel::getSingleton();
        $product_id = $params['product']['product_id'];

        $curTime = time();
        try{
            \Vendor\DB::startTrans();

            //商品基础信息
            $params['product']['update_time'] = $curTime;
            $res = $productModel->update(['product_id'=> $product_id], $params['product']);
            if(!$res){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '修改失败', $productModel->errMsg);
            }

            //商品规格属性
            $specItemsModel = SpecItemsModel::getSingleton();
            $spec_items = array_filter($params['spec_items']);
            $spec_items_index = []; //规格名称 索引 id
            foreach($spec_items as $key=>$val){
                foreach ($val as $vv){
                    //查询此商品是否添加过此属性
                    $itemInfo = $specItemsModel->find(['product_id'=> $product_id, 'item_name'=> $vv], 'item_id');
                    if(!$itemInfo){
                        $item_id = $specItemsModel->add([
                            'cat_id'        => $key,
                            'product_id'    => $product_id,
                            'item_name'     => $vv,
                        ]);
                        if(!$item_id){
                            \Vendor\DB::rollback();
                            $this->ajaxReturn(400, '修改失败.', $specItemsModel->errMsg);
                        }
                        $spec_items_index[$vv] = ['cat_id'=> $key, 'item_id'=> $item_id];
                    }else {
                        $spec_items_index[$vv] = ['cat_id'=> $key, 'item_id'=> $itemInfo['item_id']];
                    }
                }
            }

            //计算总各规格总库存
            $spec_stock_total = 0;
            foreach ($params['product_specs'] as &$val){
                $spec_stock_total += $val['spec_stock'];
            }
            //商品规格列表
            $productSpecsModel = ProductSpecsModel::getSingleton();
            foreach ($params['product_specs'] as &$val){
                $spec_ids_arr = [];
                $spec_name_full_arr = explode(' ', $val['spec_name_full']);
                foreach ($spec_name_full_arr as $vv){
                    $spec_ids_arr[] = 's'.$spec_items_index[$vv]['cat_id'].'#'.$spec_items_index[$vv]['item_id'];
                }
                $spec_ids = implode('_', $spec_ids_arr);
                $productSpecsInfo = $productSpecsModel->find(['product_id'=> $product_id, 'spec_ids'=> $spec_ids], 'spec_id');
                $updateData = [
                    'product_id'        => $product_id,
                    'spec_name_full'    => $val['spec_name_full'],
                    'spec_ids'          => $spec_ids,
                    'point'             => $val['point'],
                    'unit_money'        => $val['unit_money'],
                    'spec_stock'        => $val['spec_stock'],
                    'spec_stock_total'  => $spec_stock_total,
                    'warn_stock'        => $val['warn_stock'],
                    'is_default'        => $val['is_default'],
                    'is_show'           => 1,
                    'create_time'       => $curTime
                ];
                if(!$productSpecsInfo){
                    if(!$productSpecsModel->add($updateData)){
                        \Vendor\DB::rollback();
                        $this->ajaxReturn(400, '添加失败..', $productSpecsModel->errMsg);
                    }
                }else {
                    unset($updateData['create_time']);
                    $updateData['update_time'] = $curTime;
                    if(!$productSpecsModel->update(['spec_id'=> $productSpecsInfo['spec_id']], $updateData)){
                        \Vendor\DB::rollback();
                        $this->ajaxReturn(400, '添加失败...', $productSpecsModel->errMsg);
                    }
                }
            }

            \Vendor\DB::commit();
        }catch(Exception $e){
            \Vendor\DB::rollback();
            $this->ajaxReturn(400, '下单失败，请返回重试', $e->getMessage());
        }

        $this->ajaxReturn(0, '修改成功');
    }

    public function uploadimgAction(){
        $params = $this->post();
        if(isset($params['type']) && $params['type'] == 'cover'){

            if (!isset($_FILES['filedata'])) {
                return false;
            }
            $tmpName = $_FILES['filedata']['tmp_name'];

            $file = '';
            try {
                $file = (new \Vendor\FileModel($tmpName))->setUploadInfo($_FILES['filedata']);
            } catch (Exception $e) {
                $this->ajaxReturn(1,'请选择上传文件');
            }

            $file->validate(['size' => 1024 * 1024 * 10, 'ext' => 'jpg,png,jpeg']);
            $info = $file->move(APP_PATH . '/public/upload');
            if (!$info) {
                $this->ajaxReturn(1,$file->getError());
            }

            $img_url = \Vendor\Kstring::image_domain_url('/upload/'.$info->getSaveName());
            $this->ajaxReturn(0,'上传成功', $img_url);

        }else {

            $data = file_get_contents("php://input");
            $img_base64 = explode('base64,', $data);
            if (!$img_base64) {
                $this->ajaxReturn(1, '未获取到图片数据');
            }
            $img = base64_decode(trim($img_base64[1]));
            $img_type = explode('/', trim($img_base64[0], ';'));
            switch (strtolower($img_type[1])) {
                case 'jpeg':
                case 'jpg':
                    $img_suffix = "jpg";
                    break;
                case 'png':
                    $img_suffix = "png";
                    break;
                case 'gif':
                    $img_suffix = "gif";
                    break;
                default:
                    $img_suffix = "jpg";
            }
            $path_config = \Yaf\Application::app()->getConfig()->upload;
            $curDate = date('Ymd');
            $save_path = $path_config['path'].'/'.$curDate;
            if (!is_dir($save_path)) {
                if (!mkdir($save_path, 0755, true)) {
                    $this->ajaxReturn(400, '上传失败，文件目录不存在');
                }
            }
            $img_name =   '/' . md5(rand(1, 60000)) . "." . $img_suffix;
            file_put_contents($save_path . $img_name, $img);

            $img_url = \Vendor\Kstring::image_domain_url('/upload/'. $curDate . $img_name);
            $this->ajaxReturn(0, 'success', ['url' => $img_url]);
        }
    }

    //规格列表
    public function speccatslistAction(){
        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $specCatsModel = SpecCatsModel::getSingleton();

        $cond = [];
        if(isset($params['cate_id']) && $params['cate_id']){
            $cond['s.cate_id'] = $params['cate_id'];
        }

        $list = $specCatsModel->db
            ->alias('s')
            ->field('s.*, c.cate_title, c.cate_id')
            ->join(['cate', 'c'], ['s.cate_id'=> 'c.cate_id'], 'left join')
            ->where_c($cond)
            ->order('cat_sort desc')
            ->limit(($page - 1) * $row, $row)
            ->select();
        $total = $specCatsModel->db
            ->alias('s')
            ->join(['cate', 'c'], ['s.cate_id'=> 'c.cate_id'], 'left join')
            ->where_c($cond)
            ->count();

        $specItemsModel = SpecItemsModel::getSingleton();
        foreach ($list as &$val){
            $itemShow = [];
            $items = [];
            if(isset($params['product_id']) && $params['product_id']){
                $specItemsList = $specItemsModel->findAll(['product_id'=> $params['product_id'], 'cat_id'=> $val['cat_id']], 'item_name');
                foreach ($specItemsList as $vv){
                    $itemShow[] = ['title'=> $vv['item_name'], 'disabled'=> true];
                    $items[] = $vv['item_name'];
                }
            }
            $val['item_show'] = $itemShow;
            $val['item_input'] = '';
            $val['item'] = $items;
        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //添加
    public function speccatsaddAction(){
        $params = $this->jsonData();

        $specCatsModel = SpecCatsModel::getSingleton();
        if(!$specCatsModel->add($params)){
            $this->ajaxReturn(400, $specCatsModel->errMsg);
        }
        $this->ajaxReturn(0, '添加成功');
    }

    //修改分类
    public function speccatseditAction(){
        $params = $this->jsonData();

        if(!$params || empty($params) || !isset($params['cat_id'])){
            $this->ajaxReturn(400, '修改失败');
        }

        $specCatsModel = SpecCatsModel::getSingleton();
        $res = $specCatsModel->update(['cat_id'=> $params['cat_id']],
            [
                'cate_id'       => $params['cate_id'],
                'cat_name'      => $params['cat_name'],
                'is_show'       => isset($params['is_show'])? $params['is_show']: 1,
                'cat_sort'      => isset($params['cat_sort'])? $params['cat_sort']: 0,
                'update_time'   => time()
            ]
        );

        if(!$res){
            $this->ajaxReturn(400, '修改失败');
        }
        $this->ajaxReturn(0, '修改成功');
    }

    //商品基础表上下架
    public function proshowAction(){
        $params = $this->jsonData();

        $rule = [
            'product_id'     => 'require|number',
            'is_show'  => 'require'
        ];
        $msg = [
            'product_id.require' => '必须选择一个商品',
            'product_id.number'   => '规格ID不正确',
            'is_show.require'   => '参数错误',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        $productModel = ProductModel::getSingleton();
        if(!$productModel->update(['product_id'=> $params['product_id']], ['is_show'=> $params['is_show']])){
            $this->ajaxReturn(400, '操作失败');
        }
        $this->ajaxReturn(0, '操作成功');
    }

    //平台规格上下架
    public function specshowAction(){
        $params = $this->jsonData();

        $rule = [
            'spec_id'     => 'require|number',
            'is_show'  => 'require'
        ];
        $msg = [
            'spec_id.require' => '必须选择一个规格',
            'spec_id.number'   => '规格ID不正确',
            'is_show.require'   => '参数错误',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        //判断是否默认
        $productSpecsModel = ProductSpecsModel::getSingleton();
        $specInfo = $productSpecsModel->find(['spec_id'=> $params['spec_id']]);
        if($specInfo['is_default'] == 1){
            $this->ajaxReturn(400, '默认规格不能下架，请先更改默认项');
        }

        if(!$productSpecsModel->update(['spec_id'=> $params['spec_id']], ['is_show'=> $params['is_show']])){
            $this->ajaxReturn(400, '操作失败');
        }
        $this->ajaxReturn(0, '操作成功');
    }

    //店铺规格上下架
    public function shopspecshowAction(){
        $params = $this->jsonData();

        $rule = [
            'spec_id'     => 'require|number',
            'is_show'  => 'require'
        ];
        $msg = [
            'spec_id.require' => '必须选择一个规格',
            'spec_id.number'   => '规格ID不正确',
            'is_show.require'   => '参数错误',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        //判断是否默认
        $shopProductSpecsModel = ShopProductSpecsModel::getSingleton();
        $specInfo = $shopProductSpecsModel->find(['spec_id'=> $params['spec_id'], 'shop_id'=> $this->admin_info['shop_id']]);
        if($specInfo['is_default'] == 1){
            $this->ajaxReturn(400, '默认规格不能下架，请先更改默认项');
        }

        if(!$shopProductSpecsModel->update(['spec_id'=> $params['spec_id'], 'shop_id'=> $this->admin_info['shop_id']], ['is_show'=> $params['is_show']])){
            $this->ajaxReturn(400, '操作失败');
        }
        $this->ajaxReturn(0, '操作成功');
    }

    //店铺加入采购清单
    public function addshopcartAction(){
        $params = $this->jsonData();

        $rule = [
            'spec_id'     => 'require|number',
        ];
        $msg = [
            'spec_id.require' => '必须选择一个规格',
            'spec_id.number'   => '规格ID不正确',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        $productSpecsModel = ProductSpecsModel::getSingleton();
        $specInfo = $productSpecsModel->find(['spec_id'=> $params['spec_id']]);
        $canuse_stock = $specInfo['spec_stock']-$specInfo['f_spec_stock'];
        if($canuse_stock == 0){
            $this->ajaxReturn(400, '此规格库存为0,不能采购');
        }

        //店铺id
        $adminInfo = AdminModel::getSingleton()->find(['admin_id'=> $this->admin_info['admin_id']]);
        $uerInfo = UserModel::getSingleton()->find(['user_id'=> $adminInfo['user_id']]);
        if(!$uerInfo || $uerInfo['user_type'] != 2){
            $this->ajaxReturn('您还不是实体店铺，不能采购');
        }

        $addData = [
            'shop_id'       => $uerInfo['shop_id'],
            'product_id'    => $specInfo['product_id'],
            'spec_id'       => $specInfo['spec_id'],
            'num'           => 1,
        ];

        if(!ShopPurchaseCartModel::getSingleton()->add($addData)){
            $this->ajaxReturn(400, '操作失败，请重试');
        }

        $this->ajaxReturn(0,'加入清单成功！');
    }

    //修改采购清单购物车数量
    public function editpurcartAction(){
        $params = $this->jsonData();

        $rule = [
            'spec_id'   => 'require|number',
            'num'       => 'require|number|min:1'
        ];
        $msg = [
            'spec_id.require' => '必须选择一个规格',
            'spec_id.number'   => '规格ID不正确',
            'num.require' => '必须输入一个大于0的数量',
            'num.number'   => '数量不正确',
            'min.number'   => '数量最小为1',
        ];
        $validate = new \Vendor\Kvalidate($rule,$msg);
        if(!$validate->check($params)){
            $this->ajaxReturn(400, $validate->getError());
        }

        //计算库存
        $productSpecInfo = ProductSpecsModel::getSingleton()->find(['spec_id'=> $params['spec_id']], 'spec_stock,f_spec_stock');
        $canuse_stock = $productSpecInfo['spec_stock'] - $productSpecInfo['f_spec_stock'];
        if($canuse_stock == 0 || $canuse_stock < $params['num']){
            $this->ajaxReturn(0,'库存不足', $productSpecInfo['spec_stock']);
        }

        $cond = [
            'shop_id'=> $this->admin_info['shop_id'],
            'spec_id'=> $params['spec_id'],
        ];

        if(!ShopPurchaseCartModel::getSingleton()->update($cond, ['num'=> $params['num'], 'update_time'=> time()])){
            $this->ajaxReturn(400, '操作失败');
        }

        $this->ajaxReturn(0, '操作成功');
    }

    //删除清单
    public function delpurcartAction(){
        $params = $this->jsonData();
        if(!isset($params['spec_id']) || !$params['spec_id']){
            $this->ajaxReturn(400, '未获取到规格id');
        }

        if(!ShopPurchaseCartModel::getSingleton()->delete(['shop_id'=> $this->admin_info['shop_id'], 'spec_id'=> $params['spec_id']])){
            $this->ajaxReturn(400, '删除失败');
        }
        $this->ajaxReturn(0, '删除成功');
    }

    //计算采购总额
    public function cartmoneytotalAction(){
        $list = ShopPurchaseCartModel::getSingleton()->db
            ->field('spc.*,ps.unit_money')
            ->alias('spc')
            ->join(['product_specs', 'ps'], ['spc.spec_id'=> 'ps.spec_id'], 'left join')
            ->where_c(['spc.shop_id'=> $this->admin_info['shop_id'], 'ps.is_show'=> 1])
            ->select();

        $total = 0;
        foreach ($list as $val){
            $total += $val['unit_money'] * $val['num'];
        }

        $this->ajaxReturn(0,'success', $total);

    }

    //店铺采购记录
    public function purchaselogAction(){
        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $purchaseLogModel = PurchaseLogModel::getSingleton();

        $cond = [];
        if($this->admin_info['admin_type'] == 2){
            $cond = ['shop_id'=> $this->admin_info['shop_id']];
        }

        if(isset($params['status']) && $params['status']){
            $cond['status'] = $params['status'];
        }
        if(isset($params['date_s']) && $params['date_s'] != ''){
            $cond['create_time#>='] = $params['date_s'];
        }
        if(isset($params['date_e']) && $params['date_e'] != ''){
            $cond['create_time#<'] = $params['date_e'];
        }

        $list = $purchaseLogModel->findAll($cond);
        $total = $purchaseLogModel->count($cond);
       $shopPurchaseSpecsModel = ShopPurchaseSpecsModel::getSingleton();
        foreach ($list as &$val){
            $val['purchase_specs'] = $shopPurchaseSpecsModel->findAll(['log_id'=> $val['id']]);
            $val['status_text'] = PurchaseLogModel::$statusText[$val['status']];
        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page)
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //平台确认采购记录
    public function checkpurchaselogAction(){
        $params = $this->jsonData();
        if(!isset($params['log_id']) || !$params['log_id']){
            $this->ajaxReturn(400, '未获取到记录ID');
        }
        if(!isset($params['status']) || $params['status'] == ''){
            $this->ajaxReturn(400, '必须指定操作类型');
        }

        $purchaseLogModel = PurchaseLogModel::getSingleton();
        $shopPurchaseSpecsModel = ShopPurchaseSpecsModel::getSingleton();
        $productSpecsModel = ProductSpecsModel::getSingleton();
        $shopProductSpecsModel = ShopProductSpecsModel::getSingleton();

        $logInfo = $purchaseLogModel->find(['id'=> $params['log_id']]);
        $specList = $shopPurchaseSpecsModel->findAll(['log_id'=> $params['log_id']]);

        if(!$logInfo || !$specList){
            $this->ajaxReturn(400, '报单数据异常');
        }

        $curTime = time();
        try{
            \Vendor\DB::startTrans();

            //更新log status
            if(!$purchaseLogModel->update(['id'=> $params['log_id']], ['status'=> $params['status']])){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '操作失败。');
            }

            //更新product_spec表库存
            if($params['status'] == 1){
                foreach ($specList as $val){
                    $productSpecInfo = $productSpecsModel->find(['spec_id'=> $val['spec_id']], 'spec_stock,f_spec_stock');
                    $updateData = [
                        'spec_stock'    => $productSpecInfo['spec_stock']-$val['num'],
                        'f_spec_stock'  => $productSpecInfo['f_spec_stock']-$val['num']
                    ];
                    //更新总仓库存
                    if(!$productSpecsModel->update(['spec_id'=> $val['spec_id']], $updateData)){
                        \Vendor\DB::rollback();
                        $this->ajaxReturn(400, '操作失败..');
                    }
                    //更新店铺库存
                    $shopProductSpecsInfo = $shopProductSpecsModel->find(['spec_id'=> $val['spec_id'], 'shop_id'=> $logInfo['shop_id']]);
                    if(!$shopProductSpecsInfo){
                        $addData = [
                            'shop_id'           => $logInfo['shop_id'],
                            'product_id'        => $val['product_id'],
                            'spec_id'           => $val['spec_id'],
                            'shop_spec_stock'   => $val['num'],
                            'shop_spec_stock_total' => $val['num'],
                            'is_default'        => 0,
                            'create_time'       => $curTime
                        ];
                        $res = $shopProductSpecsModel->add($addData);
                    }else {
                        $updateData = [
                            'shop_spec_stock'   => $shopProductSpecsInfo['shop_spec_stock'] + $val['num']
                        ];
                        $res = $shopProductSpecsModel->update(['spec_id'=> $val['spec_id'], 'shop_id'=> $logInfo['shop_id']], $updateData);
                    }
                    if(!$res){
                        \Vendor\DB::rollback();
                        $this->ajaxReturn(400, '库存调入店铺仓库失败。');
                    }

                    //检查是否存在默认规格
                    $exsit = $shopProductSpecsModel->find(['shop_id'=> $logInfo['shop_id'], 'product_id'=> $val['product_id'], 'is_default'=> 1]);
                    if(!$exsit){
                        $fristData = $shopProductSpecsModel->find(['shop_id'=> $logInfo['shop_id'], 'product_id'=> $val['product_id']], 'id');
                        if(!$shopProductSpecsModel->update(['id'=> $fristData['id']], ['is_default'=> 1])){
                            \Vendor\DB::rollback();
                            $this->ajaxReturn(400, '更新店铺库存失败');
                        }
                    }
                }
            }

            \Vendor\DB::commit();
        }catch(Exception $e){
            \Vendor\DB::rollback();
            $this->ajaxReturn(400, '操作失败，请刷新重试', $e->getMessage());
        }

        $this->ajaxReturn(0, '操作成功');
    }

}
